package com.itheima.createthreaddemo;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class CreateThreadDemo3 {

    public static void main(String[] args) {

        // 创建Callable接口的实现对象
        Callable<int[]> pt = new PrimeThread3(100);
        // 创建线程任务对象
        FutureTask<int[]> ft = new FutureTask<>(pt);
        FutureTask<int[]> ft2 = new FutureTask<>(pt);
        // 创建线程对象
        Thread t = new Thread(ft);
        t.start();

        Thread t2 = new Thread(ft2);
        t2.start();

        try {
            // 获取线程执行结果
            int[] arr = ft.get();
            for (int i = 0; i < arr.length; i++) {
                System.out.println("PrimeThread3的到的素数：" + arr[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            // 获取线程执行结果
            int[] arr = ft2.get();
            for (int i = 0; i < arr.length; i++) {
                System.out.println("PrimeThread3的到的素数：" + arr[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // main线程
        CreateThreadDemo2.getPrime();

    }
}

// 创建线程的方式3：实现Callable接口，实现call()方法，创建线程对象，调用start()方法
class PrimeThread3 implements Callable<int[]> {

    public int n;
    public PrimeThread3(int n) {
        this.n = n;
    }
    public int[] call() throws Exception {
        System.out.println("PrimeThread3正在计算素数1-" + n + "...");
        int[] arr = new int[n];
        int count = 0;
        for (int i = 2; i <= n; i++) {
            boolean isPrime = true;
            for (int j = 2; j * j <= i; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                arr[count++] = i;
            }
        }
        int[] res = new int[count];
        res = Arrays.copyOf(arr, count);
        return res;
    }
}
